import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tiktokadult/assets_tool/images.dart';
import 'package:tiktokadult/hj_page/mine_business/collec_history_buy/col_his_buy_page.dart' as Col;
import 'package:tiktokadult/hj_page/mine_business/identity/mine_identity_page.dart';
import 'package:tiktokadult/hj_page/mine_business/mine_setting/close_lock_dialog.dart';
import 'package:tiktokadult/hj_page/mine_business/mine_setting/mine_password_page.dart';
import 'package:tiktokadult/hj_page/mine_business/mine_setting/mine_setting_page.dart';
import 'package:tiktokadult/hj_page/mine_business/more_question/mine_feedback_page.dart';
import 'package:tiktokadult/hj_page/mine_business/welfare/welfare_home_page.dart';
import 'package:tiktokadult/hj_page/mine_business/widgets/account_save_alert.dart';
import 'package:tiktokadult/hj_page/mine_business/widgets/no_permission_dialog.dart';
import 'package:tiktokadult/hj_page/pre_sale/pre_sale_provider.dart';
import 'package:tiktokadult/hj_utils/api_service/vid_service.dart';
import 'package:tiktokadult/hj_utils/global.dart';
import 'package:tiktokadult/hj_utils/holiday_theme.dart';
import 'package:tiktokadult/hj_utils/light_model.dart';
import 'package:tiktokadult/hj_utils/store_keys.dart';
import 'package:tiktokadult/tools_base/global_store/store.dart';
import 'package:tiktokadult/tools_base/loading/LoadingHelper.dart';

import '../../config/config.dart';
import '../../hj_model/user/user_info_model.dart';
import '../../hj_utils/flutter_base.dart';
import '../main_page/provider/msg_provider.dart';
import '../web_page/h5_page.dart';
import 'message/message_center_page.dart';
import 'mine_drive/mine_drive_page.dart';
import 'mine_following/mine_following_view.dart';
import 'mine_post/mine_publish_mian_page.dart';
import 'mine_setting/mine_code_page.dart';
import 'mine_share/mine_share_page.dart';

//图标
class IconBean {
  String image;
  String name;

  IconBean(this.image, this.name);
}

class MineMainLogic extends GetxController with GetTickerProviderStateMixin {
  RefreshController? refreshCtr;

  UserInfoModel? get userInfo => globalStore.getMe();

  List<String> get menuVerNameArr => [
        "创作中心",
        "意见反馈",
        "我的购买",
        "我的喜欢",
        "分享邀请",
        "领取兑换",
        "加群开车",
        "应用推荐",
        "账号凭证",
        "锁屏密码",
      ];

  List<IconBean> iconList = [
    IconBean(HolidayTheme.theme.appIcon, "${Config.APPNAME}"),
    IconBean('icon_1.webp'.appImgPath, "爱音乐"),
    IconBean('icon_2.webp'.appImgPath, "爱阅读"),
    IconBean('icon_3.webp'.appImgPath, "支付宝"),
    IconBean('icon_4.webp'.appImgPath, "哔哩哔哩"),
    IconBean('icon_5.webp'.appImgPath, "饼干大作战"),
    IconBean('icon_6.webp'.appImgPath, "美食借鉴"),
    IconBean('icon_7.webp'.appImgPath, "我的世界"),
    IconBean('icon_8.webp'.appImgPath, "神选之战"),
    IconBean('icon_9.webp'.appImgPath, "随心无线"),
    IconBean('icon_10.webp'.appImgPath, "特轩小说"),
    IconBean('icon_11.webp'.appImgPath, "天天麻将"),
    IconBean('icon_12.webp'.appImgPath, "途游"),
    IconBean('icon_13.webp'.appImgPath, "微信"),
    IconBean('icon_14.webp'.appImgPath, "问道"),
    IconBean('icon_15.webp'.appImgPath, "英语图书角"),
  ];

  static bool isShowedSaveQR = false;

  @override
  void onReady() async {
    super.onReady();

    if (!isShowedSaveQR) {
      isShowedSaveQR = true;
      final hasSaveQR = await lightKV.getBool(StoreKeys.HAVE_SAVE_QR_CODE);
      if (hasSaveQR != true) {
        var ret = await _showSaveQrDialog(FlutterBase.appContext!);
        if (ret == true) {
          lightKV.setBool(StoreKeys.HAVE_SAVE_QR_CODE, true);
        }
      }
    }
    onRefresh();
  }

  Future<void> getUserInfo() async {
    await globalStore.updateUserInfo();
  }

  Future<void> getWallet() async {
    await globalStore.refreshWallet();
  }

  Future<void> onRefresh() async {
    await Future.wait([
      getUserInfo(),
      MineMsgProvider().getMessageTip(),
      MineMsgProvider().getNewUserCountdown(),
      PreSaleProvider().refreshPreSaleData(), //刷新预售
      getWallet(),
    ]).whenComplete(() {
      refreshCtr?.refreshCompleted();
      update();
    });
  }

  /// 首次进入二维码页面提示保存二维码
  Future<dynamic> _showSaveQrDialog(BuildContext context) async {
    final value = await Get.dialog(AccountSaveAlert());
    if (value != null && value is UserInfoModel) {
      update();
    }
    return value;
  }

  void menuTapEvent(int index) async {
    if (index == 0) {
      //我的帖子
      Get.to(MinePublishPostPage(), preventDuplicates: false);
    } else if (index == 1) {
      //我的喜欢
      Get.to(Col.ColHisBuyPage(Col.PageType.like));
    } else if (index == 2) {
      //我的关注
      Get.to(() => MineFollowingPage());
    } else if (index == 3) {
      //消息中心
      await Get.to(() => MessageCenterPage(), opaque: true, preventDuplicates: false);
      MineMsgProvider().getMessageTip();
    }
  }

  void menuVerTapEvent(int index) async {
    if (index == 0) {
      //创作中心
      Get.to(MinePublishPostPage(), preventDuplicates: false);
    } else if (index == 1) {
      //意见反馈
      Get.toNamed(MineFeedbackPage.routeName);
    } else if (index == 2) {
      //我的购买
      Get.to(() => Col.ColHisBuyPage(Col.PageType.buy));
    } else if (index == 3) {
      //我的喜欢
      Get.to(Col.ColHisBuyPage(Col.PageType.like));
    } else if (index == 4) {
      //分享邀请
      Get.to(() => MineSharePage());
    } else if (index == 5) {
      //领取兑换
      Get.to(() => MineExchangeCodePage(type: 1));
    } else if (index == 6) {
      //加群开车
      Get.to(() => MineDrivePage());
    } else if (index == 7) {
      //应用推荐
      Get.to(WelfareHomePage(), preventDuplicates: false, arguments: 2);
    } else if (index == 8) {
      //账号凭证
      Get.to(() => const MineAccountIdentityPage());
    } else if (index == 9) {
      //锁屏密码
      if (globalStore.password.isNotEmpty) {
        final resp = await Get.dialog(CloseLockDailog());
        if (resp == true) {
          Get.toNamed(MinePasswordPage.routeNmae, arguments: MinePasswordType.close);
        }
      } else {
        Get.toNamed(
          MinePasswordPage.routeNmae,
          arguments: MinePasswordType.setting,
        );
      }
    }
  }

  toSetting(BuildContext context) {
    Get.toNamed(MineSettingPage.routeName);
  }

  toMineShare() {
    Get.to(() => MineSharePage());
  }

  toExchangeCenter() {
    Get.to(() => WelfareHomePage(), arguments: 1);
  }

  toShop() async {
    LoadingHelper.showLoading();
    var result = await VidService.getRemoteShopAddress();
    LoadingHelper.dismissLoading();
    if (result is String && result.isNotEmpty != true) {
      showToast("获取商店地址失败～");
      return;
    }
    Get.to(H5Page(url: result, showAppbar: false), popGesture: true);
  }

  changeIcon(int index) {
    Get.dialog(
      SettingNoPermissionDialog(
        content: '您确定要更换图标吗?',
        cancelTitle: '取消',
        confirmTitle: '确定',
        confirmHandler: () {
          const platform = MethodChannel('samples.flutter.io/requestApi');
          if (index == 0) {
            platform.invokeMethod('changeIcon', {"iconIndex": holidayTheme.iconIndex});
          } else {
            platform.invokeMethod('changeIcon', {"iconIndex": index});
          }
        },
      ),
    );
  }
}
